package resource 
{
	import event.CommEvent;
	import event.ResourceEvent;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	/**
	 * ...
	 * @author carlor
	 */
	public class ResourceManager 
	{
		private var _resource: Array;
		
		public function ResourceManager() 
		{
			_resource = new Array();
		}
		
		public function dispose(): void
		{
			
		}
		
		private function getFileName(fileName: String): String
		{
			return fileName.toLowerCase();
		}
		
		private function addResource(resourceName: String, resource: Resource): void
		{
			if (! resourceName || ! resource || _resource[resourceName])
				return;
			_resource[resourceName] = resource;
		}
		
		public function getResource(fileName: String, rescourceClass: Class): Resource
		{
			var resourceName: String = this.getFileName(fileName) + rescourceClass;
			return _resource[resourceName] as Resource;			
		}
		
		public function loadResource(fileName: String, rescourceClass: Class, onLoaded: Function = null, onFailed: Function = null, onLoading: Function = null): void
		{
			var resourceName: String = this.getFileName(fileName) + rescourceClass;
			var res: Resource = _resource[resourceName] as Resource;
			if (! res) {
				res = new rescourceClass();
				res.load(fileName);
				if (onLoaded != null)
					res.addEventListener(ResourceEvent.LOADED_COMPLETE, function(e: Event): void { onLoaded(res); } );
				if (onFailed != null)
					res.addEventListener(ResourceEvent.LOADED_FAILED, function(e: Event): void { onFailed(res); } );
				if (onLoading != null)
					res.addEventListener(ProgressEvent.PROGRESS, function(e: ProgressEvent): void { onLoading(e);  } );				
				addResource(resourceName, res);
			}else if (! (res is rescourceClass)) {
				trace("");
				return;
			}else {
				if (res.isLoaded) {
					if (onLoaded != null)
						onLoaded(res);
				}else {
					if (onLoaded != null)
						res.addEventListener(ResourceEvent.LOADED_COMPLETE, function(e: Event): void { onLoaded(res); } );
					if (onFailed != null)
						res.addEventListener(ResourceEvent.LOADED_FAILED, function(e: Event): void { onFailed(res); } );
					if (onLoading != null)
						res.addEventListener(ProgressEvent.PROGRESS, function(e: ProgressEvent): void { onLoading(e);  } );				
				}
			}
				
			res.incrementReferenceCount();
		}
		
		public function unloadResource(fileName: String, resourceClass: Class): void
		{
			var resourceName: String = this.getFileName(fileName) + resourceClass;
			if (! _resource[resourceName]) {
				return;
			}
			
			_resource[resourceName].decrementReferenceCount();
			if (_resource[resourceName].referenceCount <= 0) {
				_resource[resourceName].unLoad();
				_resource[resourceName] = null;
				delete _resource[resourceName];
			}
		}
	}

}